<!--renshuai-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="" prop="cateCode">
        <el-select v-model="queryParams.cateCode" filterable placeholder="请选择" clearable >
          <el-option
              v-for="item in cateOptions"
              :key="item.cateCode"
              :label="item.cateName"
              :value="item.cateCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="" prop="itemName">
        <el-input
            v-model="queryParams.itemName"
            placeholder="数据"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable>
          <el-option  v-for="(item,index) in statusList" :key="item.value" :label="item.label" :value="item.value"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['cms:cateitem:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cateItemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编码" align="center" prop="itemCode"  :show-overflow-tooltip="true"/>
      <el-table-column label="数据项" align="center" prop="itemName" :show-overflow-tooltip="true"/>
      <el-table-column label="产品" align="center" prop="cateCode">
        <template slot-scope="scope">
          <span v-for="(item,index) in cateOptions" :key="index" v-if="item.cateCode==scope.row.cateCode">
            {{ item.cateName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="itemImg" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-image
              v-if="!!scope.row.itemImg"
              style="width: 60px; height: 60px; margin-bottom:-4px"
              :src="scope.row.itemImg"
              :preview-src-list="[scope.row.itemImg]"
              lazy
          >
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sortNum" :show-overflow-tooltip="true"/>
      <el-table-column label="状态" align="center" prop="status" width="90">
        <template slot-scope="scope">
          <dict-tag :options="statusList" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
              type="text"
              size="small"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['cms:cateitem:edit']">修改</el-button>
          <el-button
              type="text"
              size="small"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['cms:cateitem:del']">删除</el-button>
          <el-button
              type="text"
              size="small"
              icon="el-icon-view"
              @click="handlePreview(scope.row)"
              v-hasPermi="['cms:cateitem:preview']">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改话框 -->
    <el-dialog :title="title" :visible.sync="open" width="780px" append-to-body center :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="编码" prop="itemCode">
              <el-input v-model="form.itemCode" :disabled="!isAdd"/>
            </el-form-item>
          </el-col>
          <el-col  :span="24">
            <el-form-item label="产品" prop="cateCode">
              <el-select v-model="form.cateCode" filterable placeholder="请选择" clearable >
                <el-option
                    v-for="item in cateOptions"
                    :key="item.cateCode"
                    :label="item.cateName"
                    :value="item.cateCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数据项" prop="itemName">
              <el-input v-model="form.itemName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12" >
            <el-form-item label="状态" prop="status">
              <el-switch
                  v-model="form.status"
                  active-value="1"
                  inactive-value="0"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="排序" prop="sortNum">
              <el-input v-model="form.sortNum"/>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="产品图片" prop="itemImg">
              <el-upload
                  class="thmb-uploader"
                  :action="uploadAction"
                  accept="image/jpg,image/png,image/jpeg"
                  :on-exceed="handleExceed"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :headers="headers"
                  :auto-upload="true" :file-list="fileList"
                  :on-success="handleSuccessImg"
                  :on-progress="handleProcessImg"
                  :on-remove="handleRemove"
              >
                <i class="el-icon-circle-close" v-if="form.itemImg" @click.stop="handleRemove"></i>
                <img v-if="form.itemImg" :src="form.itemImg" class="thmb-img ">
                <i v-else class="el-icon-plus thmb-uploader-icon"></i>

                <el-progress
                    :width="100"
                    v-if="imageUploading"
                    type="circle"
                    v-bind:percentage="imageUploadPercent"
                    class="thmb-img-progress"
                ></el-progress>

              </el-upload>

            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-table v-loading="loading" :data="form.projItemList">
            <el-table-column label="序号" width="50px" align="center">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="编码" align="center" prop="projCode"  :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-input  v-model="scope.row.projCode" readonly/>
              </template>
            </el-table-column>
            <el-table-column label="服务项目" align="center" prop="projName">
              <template slot-scope="scope">
                <el-form-item label-width="0px" style="margin-bottom: 0px;;"
                              :status-icon="true"
                              :rules="[
                                    { required: true, message: '请输入服务类型', trigger: ['blur', 'change'] }
                                  ]"
                              :prop="'projItemList.' + scope.$index +'.projCode'">
<!--                <el-input  v-model="scope.row.projName"/>-->
                    <el-select v-model="scope.row.projCode" placeholder="服务类型" clearable style="width: 120px"
                               >
                      <el-option v-for="(item ,index) in projList"
                                 :key="item.projCode" :label="item.projName"
                                 :value="item.projCode"
                                 @click.native="handleClickProj(scope.$index,item)"/>
                    </el-select>
                </el-form-item>
              </template>

            </el-table-column>
            <el-table-column label="厂商最低报价限制" align="center" prop="priceFloor">
              <template slot-scope="scope">
                <el-form-item :rules="rules.priceFloor" :prop="'projItemList.' + scope.$index +'.priceFloor'"
                              label-width="0px" style="margin-bottom: 0px;;"
                              :status-icon="true">
                  <el-input  v-model="scope.row.priceFloor"
                             oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="平台抽成%" align="center" prop="svcFeePct" width="140">
              <template slot-scope="scope">
                <el-form-item :rules="rules.svcFeePct" :prop="'projItemList.' + scope.$index +'.svcFeePct'"
                              label-width="0px" style="margin-bottom: 0px;;"
                              :status-icon="true">
                  <el-input  v-model="scope.row.svcFeePct"
                             oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}">
                    <template slot="append">%</template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" :render-header="renderHeader">
              <template slot-scope="scope">
                <el-button
                    type="text"
                    icon="el-icon-plus"
                    size="mini"
                    v-if="scope.$index == form.projItemList.length-1"
                    @click="handleAddRow()"
                >新增</el-button>
                <el-button
                    type="text"
                    size="small"
                    icon="el-icon-delete"
                    @click="handleDeleteRow(scope.$index,scope.row)"
                    >删除</el-button>
              </template>
            </el-table-column>

          </el-table>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onSubmitForm" v-if="openIsEdit">保 存</el-button>
        <el-button @click="handleClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getCateOptionselect} from "@/api/cms/prod/cate";
import {
  delCateItemByCode,
  getCateItemByCode,
  insertItem,
  listCateItem,
  listProjItem,
  updateItem
} from "@/api/cms/prod/cateItem";
import {uploadFile} from "@/api/upload";
import {getSystem, getToken} from "@/utils/auth";
import {listProjAct} from "@/api/cms/prod/proj";

export default {
  name: "CateItemList",
  data() {
    return {
      cateOptions: [],
      statusList:[
        {
          raw:{
            listClass:"default",
            cssClass:""
          },
          value:"",
          label:"全部"
        },
        {
          raw:{
            listClass:"primary",
            cssClass:""
          },
          value:"1",
          label:"正常"
        },
        {
          raw:{
            listClass:"info",
            cssClass:""
          },
          value:"0",
          label:"关闭"
        }
      ],
      projList:"",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      cateItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isAdd:false,//是否新增
      //是否打开编辑
      openIsEdit:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: undefined,
        cateCode: undefined,
        itemName:undefined,
        itemNameComp:"like",
      },
      // 表单参数
      form: {
        projItemList:[],
        itemImg:undefined,
      },
      // 表单校验
      rules: {
        itemName:  [
          {
            validator:(rule, value, callback)=>{
              if(!value){
                callback(new Error("名称不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '名称不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required: true }
        ],
        itemCode: [
          {
            validator:(rule, value, callback)=>{
              if(!value){
                callback(new Error("编码不能为空"))
                this.$notify.error({
                  title: '错误',
                  message: '编码不能为空'
                });
              }else{
                callback(); //成功后不传入错误参数即可
              }
            }, trigger: "blur",required: true }
        ],
        svcFeePct: [
          {
            required: true,
            message: '请输入',
            trigger: 'change'
          }
        ],
        priceFloor: [
          {
            required: true,
            message: '请输入',
            trigger: 'change'
          }
        ]
      },
      uploadAction:uploadFile,
      headers: {
        // Authorization: "Bearer " + getToken()
        'access-token': getToken(), // 让每个请求携带自定义token 请根据实际情况自行修改
        'system-key': getSystem()
      },
      fileList:[],
      imageUploading:false,//图片是否上传中
      imageUploadPercent:0,//图片上传百分比
    };
  },
  created() {
    const  cateCode= this.$route.params && this.$route.params.cateCode;
    if(!!cateCode){
      this.$set(this.queryParams,"cateCode", cateCode)
    }

    this.getCateOptions();
    this.getList();
    this.getProjList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      listCateItem(this.queryParams).then(response => {
        this.cateItemList = response.data;
        this.total = response.total != NaN ?Number(response.total):undefined;
        this.loading = false;
      });
    },
    /**
     * 查询服务项目
     */
    getProjList(){
      listProjAct().then(response =>{
        this.projList=response.data;
      });
    },

    getListProjItem(itemCode){
      listProjItem(itemCode).then(response => {
        this.$set(this.form,"projItemList", response.data)
        //this.form.formProjItemList = response.data;
      })
    },

    /**
     * 产品类别的选择内容
     */
    getCateOptions(){
      getCateOptionselect().then(response => {
        this.cateOptions = response.data;
      });
    },

    handleAddRow(){
      this.form.projItemList.push({

      })
    },
    handleDeleteRow(index,row){
      this.form.projItemList.splice(index,1);
    },
    handleClickProj(index,obj){
      //判断数据项是否已经被使用
      for(let arr in this.form.projItemList){
        if(arr!=index){
          if(this.form.projItemList[arr].projCode==obj.projCode){
            this.$message.warning("数据项【"+obj.projName+"】已经存在，请重新选择")
            this.form.projItemList[index].projCode=undefined;
            return;
          }
        }
      }

      this.form.projItemList[index].projName=obj.projName;
    },
    /**
     * 详情按钮
     * @param row
     */
    handleUpdate(row){
      this.openIsEdit=true;
      let itemCode=row.itemCode;
      getCateItemByCode(itemCode).then(response => {
        this.form = response.data;
        this.open = true;
        this.isAdd=false;
        this.title = "详细信息";

        this.getListProjItem(itemCode);

      });
    },

    /**
     * 详情按钮
     * @param row
     */
    handlePreview(row){
      this.handleUpdate(row);
      this.openIsEdit=false;
    },
    renderHeader(){
      return (
          <div>
            <span>操作</span>
            <el-button style="margin-left:5px;padding-left:5px;padding-right:5px"
                type="primary"
                plain
                icon="el-icon-plus"
                class="table-icon"
                size="mini"
                onClick={() => this.handleAddRow()}
            >新增</el-button>
          </div>
      );
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.itemName + '"的数据项？').then(function() {
        return delCateItemByCode(row.itemCode);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    onSubmitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.isAdd){
            insertItem(this.form).then(response => {
              this.$modal.msgSuccess("保存成功");
              this.open = false;
              this.getList();
            });
          }else{
            updateItem(this.form).then(response => {
              this.$modal.msgSuccess("保存成功");
              this.open = false;
              this.getList();
            });
          }


        }else{
          this.$notify.error({
            title: '错误',
            message: '信息填报不完整'
          });
        }
      });
    },

    handleAdd(){
      this.reset();
      this.open = true;
      this.isAdd= true;
      this.openIsEdit=true;
      this.title = "新增";
      //this.getListProjItem()
    },

    // 取消按钮
    handleClose() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        projItemList:[],
        itemCode:undefined,
        itemName:undefined,
        status: "1"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.noticeId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },


    handleExceed(files, fileList) {
      this.$message.warning(`当前限制最多上传一张图片`)
    },
    beforeAvatarUpload(file) {
      let isJPG = false
      let isLt10M = file.size / 1024 / 1024 < 10
      if (
          file.type === 'image/jpeg' ||
          file.type === 'image/png' ||
          file.type === 'image/jpg'
      ) {
        isJPG = true
      } else {
        isJPG = false
      }
      if (!isJPG) {
        this.$message.error('上传图片只能是 jpg/jpeg/png 格式!')
      }
      if (!isLt10M) {
        this.$message.error('上传图片大小不能超过 10M!')
      }
      return isJPG && isLt10M
    },
    handleSuccessImg(response, file, fileList) {
      this.imageUploading=false;
      if (response.code === 200) {
        this.form.itemImg =response.data.url;
      } else {
        this.$message.error('上传失败，请重试');
        this.form.itemImg  = undefined;
      }
    },
    handleProcessImg(event, file, fileList) {    //注意在data中添加对应的变量名
      this.imageUploading = true
      this.imageUploadPercent = file.percentage.toFixed(0) * 1
    },
    handleRemove(file, fileList) {
      this.form.itemImg = undefined;
    },
  }
};
</script>
<style lang="scss" scoped>
/***上传**/
::v-deep.thmb-uploader .el-upload {
  border: 1px dashed #D9D9D9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep.thmb-uploader .el-upload:hover {
  border-color: #409EFF;
}

.thmb-img {
  width: 100px;
  height: 100px;
  display: block;
}

.thmb-uploader:hover .el-icon-circle-close {
  visibility: visible;
}
.el-icon-circle-close {
  /*display: flex;
  float: right;
  margin-right: 6px;*/
  right: 2px;
  color: #959bcb;
  font-size: 30px;
  visibility: hidden;
  position: absolute;
  z-index: 99;
}
.thmb-img-progress{
  left: 0px;
  //right: 0px;
  //bottom:0px;
  //top:0px;
  position: absolute;
}
.thmb-uploader-icon {
  font-size: 28px;
  color: #8C939D;
  width: 100px;
  height: 100px;
  line-height: 108px;
  text-align: center;
}

</style>